<template>
  <div class="newWindow">
    <div class="conten">
      <h4 class="T-title">
        {{ PowerStationId ? $t('licence.powe_title1') : $t('licence.powe_title2') }}
      </h4>
      <div class="conten-main">
        <el-form :inline="true" label-position="left" label-width="120px" :rules="rules" :model="electricForm"
          ref="electricFormRef">
          <!-- 联系信息 -->
          <h4 class="title">{{ $t('licence.powe_title3') }}</h4>
          <el-form-item :label="$t('licence.cus_nickName')" prop="nickName">
            <el-input v-model="electricForm.nickName" :placeholder="$t('licence.powe_shunickName')"
              :disabled="disabled"></el-input>
          </el-form-item>
          <el-form-item :label="$t('licence.cus_userName')" prop="userName">
            <el-input :value="electricForm.userName" v-model="electricForm.userName"
              :placeholder="$t('licence.powe_userName')" :disabled="disabled"></el-input>
            <div class="selection" @click="getTerminalList">
              {{ $t('licence.powe_getTermina') }}
            </div>
            <div class="selection cancel" v-if="cancelShow" @click="cancelTerminalList">
              {{ $t('licence.powe_cancelTerminal') }}
            </div>
          </el-form-item>
          <el-form-item :label="$t('licence.dep_phone')" prop="phone">
            <el-input v-model="electricForm.phone" :placeholder="$t('licence.dep_phone2')"
              :disabled="disabled"></el-input>
          </el-form-item>
          <el-form-item label="Email" prop="email">
            <el-input v-model="electricForm.email" :placeholder="$t('licence.powe_email')"
              :disabled="disabled"></el-input>
          </el-form-item>
          <!-- 基础信息 -->
          <h4 class="title">{{ $t('licence.powe_title4') }}</h4>
          <el-form-item :label="$t('licence.stationName')" prop="stationName">
            <el-input v-model="electricForm.stationName" :placeholder="$t('licence.powe_shustationName')"></el-input>
          </el-form-item>
          <!-- 电站类型 -->
          <el-form-item :label="$t('licence.powe_type')" prop="stationType">
            <el-select style="width: 300px" v-model="electricForm.stationType" :placeholder="$t('licence.powe_shutype')">
              <el-option v-for="dict in lang == 1 ? sys_station_type_en : sys_station_type" :key="dict.value"
                :label="dict.label" :value="dict.value * 1"></el-option>
            </el-select>
          </el-form-item>
          <!-- {{ electricForm.province }} -->
          <el-form-item :label="$t('licence.powe_province')" prop="province">
            <!-- 电站地区-->
            <el-cascader v-model="electricForm.province" :options="addOptions" :props="{ checkStrictly: true }"
              ref="cascaderArr" style="width: 300px" @change="handleChange"
              :placeholder="$t('licence.powe_xuanzeAdd')"></el-cascader>
          </el-form-item>
          <el-form-item :label="$t('licence.powe_address')" prop="address">
            <el-input v-model="electricForm.address" :placeholder="$t('licence.powe_shuaddress')" disabled></el-input>
            <div class="selectionAdd" @click="getMap">
              <img class="addIcon" src="../../assets/images/add.png" alt="" />
              <span style="margin-left: 5px">{{ $t('licence.powe_selectionAdd') }}</span>
            </div>
            <!-- 百度地图显示 -->
            <pointer-map @detailAdress="detailAdress" ref="pointerMaps"></pointer-map>
          </el-form-item>
          <el-form-item :label="$t('licence.poweCapacity')" prop="installedCapacity">
            <el-input v-model="electricForm.installedCapacity" :placeholder="$t('licence.poweInpCapacity')"></el-input>
          </el-form-item>

          <el-form-item :label="$t('licence.powe_price')" prop="price">
            <el-input v-model="electricForm.price" :placeholder="$t('licence.powe_shuprice')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('licence.powe_avatar')" prop="avatar" style="width:400px">
            <div class="user-info-head" @click="editCropper()">
              <img v-bind:src="options.img" :title="$t('licence.powe_avatar')" class="img-circle img-lg" />
            </div>
          </el-form-item>
          <el-form-item :label="$t('licence.powe_poweRemark')" prop="remark">
            <el-input :rows="8" type="textarea" v-model="electricForm.remark" style="width: 820px"
              :placeholder="$t('licence.powe_remark')"></el-input>
          </el-form-item>
          <div class="Button">
            <el-button @click="resetForm()">{{ $t('licence.upperStep') }}</el-button>
            <el-button style="background: #305add; border: none" type="primary" @click="submitForm()">{{
              $t('licence.nextStep') }}</el-button>
          </div>
        </el-form>
        <!-- 选取用户列表 -->
        <el-dialog v-model="selectionShow" width="40%">
          <div class="titleShow">
            <div class="titles">{{ $t('licence.powe_userList') }}</div>
          </div>
          <el-input v-model="searchValue" :placeholder="$t('licence.cus_searchValue')"
            style="margin-right: 20px"></el-input>
          <el-button @click="getTerminalList" type="primary" style="margin: 20px 0">{{ $t('licence.fau_Thequery')
          }}</el-button>
          <el-table :data="selectionList" @row-click="selectionClick">
            <el-table-column property="userName" :label="$t('licence.cus_userName')" width="200"></el-table-column>
            <el-table-column property="phone" :label="$t('licence.dep_phone')" width="150"></el-table-column>
            <el-table-column property="email" :label="$t('licence.use_email')"></el-table-column>
          </el-table>
          <!-- 分页区 -->
          <div class="block" style="margin: 20px">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="queryData.page" :page-size="queryData.pagesize" :page-sizes="[2, 4, 6, 8, 10]"
              layout="sizes, prev, pager, next,total, jumper" :total="queryData.total"> </el-pagination>
          </div>
        </el-dialog>
        <!-- 头像上传==== -->
        <el-dialog v-model="open" :title="$t('licence.powe_title5')" width="800px" append-to-body @opened="modalOpened" @close="closeDialog">
          <!-- <div class="titleShow">
            <div class="titles">{{ $t('licence.powe_title5') }}</div>
          </div> -->
          <el-row>
            <el-col :xs="24" :md="12" :style="{ height: '350px' }">
              <vue-cropper ref="cropper" :img="options.img" :info="true" :autoCrop="options.autoCrop"
                :autoCropWidth="options.autoCropWidth" :autoCropHeight="options.autoCropHeight"
                :fixedBox="options.fixedBox" :outputType="options.outputType" @realTime="realTime" v-if="visible" />
            </el-col>
            <el-col :xs="24" :md="12" :style="{ height: '350px' }">
              <div class="avatar-upload-preview">
                <img :src="previews.url" :style="previews.img" />
              </div>
            </el-col>
          </el-row>
          <br />
          <el-row>
            <el-col :lg="2" :md="2">
              <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
                <el-button size="small">
                  {{ $t('licence.sys_xuanze') }}
                  <el-icon><UploadFilled /></el-icon>
                </el-button>
              </el-upload>
            </el-col>
            <el-col :lg="{ span: 1, offset: 2 }" :md="2">
              <el-button icon="Plus" size="small" @click="changeScale(1)"></el-button>
            </el-col>
            <el-col :lg="{ span: 1, offset: 1 }" :md="2">
              <el-button icon="Minus" size="small" @click="changeScale(-1)"></el-button>
            </el-col>
            <el-col :lg="{ span: 1, offset: 1 }" :md="2">
              <el-button icon="RefreshLeft" size="small" @click="rotateLeft()"></el-button>
            </el-col>
            <el-col :lg="{ span: 1, offset: 1 }" :md="2">
              <el-button icon="RefreshRight" size="small" @click="rotateRight()"></el-button>
            </el-col>
            <el-col :lg="{ span: 2, offset: 6 }" :md="2">
              <el-button type="primary" size="small" @click="uploadImg()">{{ $t('licence.powe_tijiao') }}</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { addelectric, getTerminalLists, getPowerStationDetails, editorPowerStation, uploadStationAvatar, getAddZh } from '@/api/powerStation/powerStation';
import { getAdds } from '@/api/homeIndex';
import PointerMap from '@/views/components/pointer-map.vue';
import "vue-cropper/dist/index.css";
import { VueCropper } from 'vue-cropper'; //照片裁剪修改
import { useI18n } from 'vue-i18n'
import { isHttp } from '@/utils/validate';
const { t } = useI18n()
const cropper = ref()

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { sys_station_type_en, sys_station_type, sys_dst_en, sys_dst } = toRefs<any>(proxy?.useDict('sys_station_type_en', 'sys_station_type', 'sys_dst_en', 'sys_dst'));//功率段
// 是否显示弹出层
const open = ref(false);
// 是否显示cropper
const visible = ref(false);
const options = ref({
  img: 'https://image.dhhome-e.com:9000/daheng/avatar/a15387d4-7471-4473-ac08-a4d1a119be74.png', //裁剪图片的地址
  autoCrop: true, // 是否默认生成截图框
  autoCropWidth: 200, // 默认生成截图框宽度
  autoCropHeight: 200, // 默认生成截图框高度
  fixedBox: true, // 固定截图框大小 不允许改变
  outputType: 'png',
});
const previews = ref({
  url: '',
  img: '',
});
// ===========
const electricFormRef = ref()
const pointerMaps = ref()
const cascaderArr = ref(null)
const userInfo = ref({
  dept: {
    countryCode: ''
  }
}); //获取用户信息
// 用户表单
let electricForm = ref({
  userId: '', //选取用户保存的id
  avatar: '',
  avatarOss:'',
  nickName: '',
  userName: '',
  phone: '',
  email: '',
  stationName: '',
  price: '',
  stationType: '',
  dst: '',
  province: [],
  city: '',
  district: '',
  address: '',
  remark: '',
  // provinceName: [], //省市区
  gpsLngValue: '', //经度
  gpsLatValue: '', //纬度
  installedCapacity: 0
});
const rules = reactive({
  userName: [
    {
      required: true,
      message: t('licence.powe_userName'),
      trigger: 'blur',
    },
  ],
  // phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  email: [
    {
      required: true,
      message: t('licence.for_email'),
      trigger: 'blur',
    },
  ],
  stationName: [
    {
      required: true,
      message: t('licence.powe_stationNameMess'),
      trigger: 'blur',
    },
  ],
  stationType: [
    {
      required: true,
      message: t('licence.powe_typeMess'),
      trigger: 'blur',
    },
  ],
  province: [
    {
      required: true,
      message: t('licence.powe_provinceMess'),
      trigger: 'blur',
    },
  ],
  address: [
    {
      required: true,
      message: t('licence.powe_shuaddress'),
      trigger: 'blur',
    },
  ],
});
const selectionShow = ref(false); //选取用户列表
const selectionList = ref([]); //用户列表
const searchValue = ref(''); //搜索用户参数
const disabled = ref(false); //选择用户后不可编辑
const cancelShow = ref(false); //取消选择的显示与隐藏
// const baiduShow = ref(false); //地图
const center = reactive({ lat: 45.508, lng: -73.587 }); //地图
//头像
// const imageUrl = ref('');
// 省市级
// const label = ref([]);
const addOptions = ref([]);
const stationDetail = ref({})//用于对比编辑页提交前的数据对比
// 分页
const queryData = reactive({
  page: 1,
  pagesize: 10,
  total: 0 as number
});
const lang = ref(0);
const regionIds = ref([]); //保存地区的value
const route = useRoute()
const router = useRouter()
const PowerStationId = route.query.id as string //单个电站id
console.log('route:', route)
onMounted(() => {
  // 获取用户信息
  userInfo.value = JSON.parse(localStorage.getItem('userInfo') as string);
  // 获取语言
  if (localStorage.getItem('locale') == 'en_US') {
    lang.value = 1;
  } else {
    lang.value = 0;
  }

  // 电站地址 省市级
  getAdd();
  //获取电站详情
  if (PowerStationId) {
    getPowerStationDetail();
  }
})
// 编辑头像
const editCropper = () => {
  open.value = true;
};
// 打开弹出层结束时的回调
const modalOpened = () => {
  visible.value = true;
};
// 覆盖默认的上传行为
const requestUpload = () => { };
// 向左旋转
const rotateLeft = () => {
  cropper.value.rotateLeft();
};
// 向右旋转
const rotateRight = () => {
  cropper.value.rotateRight();
};
// 图片缩放
const changeScale = (num: number) => {
  num = num || 1;
  cropper.value.changeScale(num);
};
// 实时预览
const realTime = (data: any) => {
  previews.value = data;
};
// 关闭窗口
const closeDialog = () => {
  // options.value.img = store.getters.stationAvatar;
  visible.value = false;
};
// 上传预处理
const beforeUpload = (file: any) => {
  if (file.type.indexOf('image/') == -1) {
    proxy?.$modal.msgError(t('licence.powe_beforeUpload'));
  } else {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      options.value.img = reader.result as string;
    };
  }
};
// 上传图片
const uploadImg = () => {
  cropper.value.getCropBlob((data: any) => {
    let formData = new FormData();
    formData.append('avatarfile', data,'a.png');
    console.log('formData:', formData)
    let res = {
      lang: 0,
    };
    uploadStationAvatar(formData).then((response) => {
      open.value = false;
      options.value.img = response.data.imgUrlOss?response.data.imgUrlOss:import.meta.env.VITE_IMG_BASE_API + response.data.imgUrl;
      electricForm.value.avatar = response.data.imgUrl;
      electricForm.value.avatarOss = response.data.imgUrlOss;
      // store.commit("SET_SAVATAR", options.value.img);
      proxy?.$modal.msgSuccess(t('licence.use_updateXiugai'));
      visible.value = false;
    });
  });
};
// 地图
// 百度地图
const getMap = async () => {
  let query = {
    regionIds: regionIds.value.join(','),
    lang: lang.value,
  };
  let { data } = await getAddZh(query);
  if (electricForm.value.province.length > 0) {
    // 传值省市县给地图页面
    nextTick(() => {
      pointerMaps.value.init(data);
    })
  } else {
    ElMessage.error(t('licence.powe_addMess'));
  }
};
// 省市级选择
const getAdd = async () => {
  let res = await getAdds({
    code: userInfo.value.dept.countryCode,
    lang: lang.value,
  });
  addOptions.value = res.data;
};
const detailAdress = async (adress: any, lat: any, lng: any) => {
  electricForm.value.address = adress;
  electricForm.value.gpsLatValue = lat;
  electricForm.value.gpsLngValue = lng;
};
const handleChange = (value: any) => {
  regionIds.value = value;
  // electricForm.value.provinceName = cascaderArr.value.getCheckedNodes()[0].pathLabels;
};
// 表单取消
const resetForm = () => {
  electricFormRef.value?.resetFields();
  router.go(-1);
};
// 获取电站详情
const getPowerStationDetail = async () => {
  let res = await getPowerStationDetails(PowerStationId);
  stationDetail.value = res.data//用于对比编辑页提交前的数据对比
  nextTick(() => {
    if (localStorage.getItem('locale') == 'en_US') {
      electricForm.value = {
        ...res.data,
        province: [
          String(res.data.city),
          // String(res.data.district),
        ],
        provinceName: [
          res.data.provinceName,
          res.data.cityName,
          // res.data.districtName,
        ]
      };
    } else {
      electricForm.value = {
        ...res.data,
        province: [String(res.data.province), String(res.data.city), String(res.data.district)],
        // provinceName:[res.data.provinceName, res.data.cityName, res.data.districtName]
      };
    }
  })
  options.value.img = res.data.avatarOss?res.data.avatarOss:import.meta.env.VITE_IMG_BASE_API + res.data.avatar;
};

// 表单确定
const submitForm = async () => {
  await electricFormRef.value.validate();
  let res: any;
  let type: number | string = electricForm.value.stationType;
  // 编辑电站
  if (PowerStationId) {
    let data = {
      ...electricForm.value,
      id: PowerStationId,
      province: electricForm.value.province[0], //省
      city: electricForm.value.province[1], //市
      district: electricForm.value.province[2], //县
      userId: electricForm.value.userId || '', //用户ID
    }
    delete data.stationName //编辑电站不允许修改电站类型
    // delete data.provinceName

    res = await editorPowerStation(data);
    if (res.code == '200') {
      ElMessage.success(t('licence.powe_bainji'));
    } else {
      return;
    }
    setTimeout(() => {
      if(type == 3) {
        // router.push({
        //   path: `/equipmentList?id=${PowerStationId}`,
        // });
        router.push({ path: 'equipmentList', query: { id: PowerStationId } })
      } else {
        // router.push({
        //   path: `/gatewayList?id=${PowerStationId}`,
        // });
        router.push({ path: 'gatewayList', query: { id: PowerStationId } })
      }
    }, 2000);
  } else {
    // 创建电站
    electricFormRef.value.validate(async () => {
      let data = {
        ...electricForm.value,
        id: PowerStationId,
        province: electricForm.value.province[0], //省
        city: electricForm.value.province[1], //市
        district: electricForm.value.province[2], //县
        userId: electricForm.value.userId || '', //用户ID
      }
      // delete data.provinceName
      res = await addelectric(data);
      if (res.code == '200') {
        ElMessage.success(t('licence.powe_chaungjian'));
      } else {
        return;
      }
      setTimeout(() => {
        if(type == 3) router.push({ path: 'equipmentList', query: { id: res.data.id } })
        else router.push({ path: 'gatewayList', query: { id: res.data.id } })
      }, 2000);
    });
  }
  // ElMessage.success(PowerStationId ? "编辑成功" : "创建成功");

  // electricForm.value = {
  //   nickName: '',
  //   userName: '',
  //   phone: '',
  //   email: '',
  //   stationName: '',
  //   stationType: '',
  //   dst: '',
  //   price: '',
  //   province: '',
  //   city: '',
  //   district: '',
  //   address: '',
  //   remark: '',
  //   installedCapacity: '',
  // };
};
//选择用户弹框 获取用户列表
const getTerminalList = async () => {
  selectionShow.value = true;
  let res = await getTerminalLists({
    pageNum: queryData.page,
    pageSize: queryData.pagesize,
    searchValue: searchValue.value,
  });
  queryData.total = res.data.total;
  selectionList.value = res.data.list;
};

// 分页
const handleSizeChange = (val: number) => {
  queryData.pagesize = val;
  getTerminalList();
};
const handleCurrentChange = (val: number) => {
  queryData.page = val;
  getTerminalList();
};
// 选择用户确定
const selectionClick = (row: any) => {
  electricForm.value.userId = row.id;
  electricForm.value.nickName = row.nickName;
  electricForm.value.userName = row.userName;
  electricForm.value.phone = row.phone;
  electricForm.value.email = row.email;
  selectionShow.value = false;
  disabled.value = true;
  cancelShow.value = true;
};
const cancelTerminalList = () => {
  electricForm.value.userId = '';
  electricForm.value.nickName = '';
  electricForm.value.userName = '';
  electricForm.value.phone = '';
  electricForm.value.email = '';
  disabled.value = false;
  cancelShow.value = false;
};
</script>

<style scoped lang="scss">
* {
  // margin: 0;
  box-sizing: border-box;
  list-style: none;
}

// 查询按钮
.el-button--primary {
  color: #ffffff;
  background-color: #305add;
  border-color: #305add;
}

// 头像上传
.user-info-head {
  position: relative;
  display: inline-block;
  height: 70px;
  text-align: center;
}

.user-info-head:hover:after {
  content: '+';
  text-align: center;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  color: #eee;
  background: rgba(0, 0, 0, 0.5);
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  cursor: pointer;
  line-height: 70px;
  border-radius: 50%;
}

//百度地图

#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

#allmap {
  height: 800px;
  overflow: hidden;
}

.conten {
  width: 1200px;
  // height: 700px;
  background: #ffffff;
  border-radius: 6px;
  padding: 30px 0;
  margin: auto;

  .T-title {
    padding: 0 0 30px 20px;
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 600;
    margin-bottom: 24px;
    border-bottom: 1px solid #ececec;
  }

  .conten-main {
    padding: 0 30px;

    .title {
      padding-left: 4px;
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 600;
      margin-bottom: 24px;
      border-left: 2px solid #305add;
    }

    // input框长度
    .el-input {
      width: 300px;
    }

    // 宽度
    ::v-deep .el-input--mini .el-input__inner {
      height: 40px !important;
      line-height: 40px !important;
    }

    ::v-deep .el-form-item--mini .el-form-item__label {
      line-height: 40px !important;
    }

    .el-form-item--mini.el-form-item {
      display: inline-block;
      margin-right: 95px;
      margin-bottom: 30px;
      vertical-align: text-top;
    }
  }

  //   头像
  ::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 84px;
    height: 84px;
    box-sizing: border-box;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }

  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }

  //   提交 取消按钮
  .Button {
    margin: auto;
    display: table;
    margin-top: 20px;
  }

  // 选取用户
  .selection,
  .selectionAdd {
    position: absolute;
    right: -80px;
    top: 7px;
    color: #305add;
    cursor: pointer;
  }

  .cancel {
    right: -190px;
  }

  .selectionAdd {
    color: #999999;
    right: -135px;

    .addIcon {
      width: 18px;
      height: 20px;
      vertical-align: middle;
    }
  }

  .yonghu {
    border-bottom: 1px solid #ececec;
    padding-bottom: 10px;
    margin-bottom: 20px;
  }

  ::v-deep .el-dialog {
    width: 45%;
    border-radius: 6px;
  }
}

// 弹框的标题修改
.titleShow {
  display: flex;
  cursor: pointer;
  font-size: 16px;
  margin-right: 24px;
  font-weight: 600;
  border-bottom: 1px solid #eee;
  width: 100%;
  padding-bottom: 20px;

  .titles {
    margin-right: 24px;
  }
}

::v-deep .el-dialog__header {
  padding: 0 !important;
  padding-bottom: 0;
}

::v-deep .el-dialog {
  border-radius: 6px;
}

::v-deep .el-dialog__body {
  padding: 20px;
}

// 弹框里的分页
.block {
  // display: flex;
  display: -webkit-box;
  justify-content: end;
}
::v-deep .vue-cropper{
  height: 350px;
}
</style>
